#include <memory>
#include <thread>
#include <chrono>
#include <fstream>
#include <atomic>
#include <future>
#include <csignal>
#include <spdlog/spdlog.h>
#include <spdlog/sinks/stdout_color_sinks.h>
#include <nlohmann/json.hpp>

#include "event_bus.h"
#include "events.h"

#include "log_manager.h"
#include "risk/risk_manager.h"
#include "execution/order_manager.h"
#include "execution/execution_engine.h"

using json = nlohmann::json;

// 系统常量定义
namespace {
    constexpr auto CONFIG_FILE = "config/system_config.json";
    constexpr auto RISK_CONFIG_FILE = "config/risk_config.json";
    constexpr auto STATE_FILE = "system_state.json";
    constexpr auto LOG_FLUSH_INTERVAL = std::chrono::hours(24);
    constexpr auto MONITOR_INTERVAL = std::chrono::seconds(5);
    constexpr auto MAX_LOG_SIZE = 10 * 1024 * 1024; // 10MB
    constexpr auto MAX_LOG_FILES = 5;
    constexpr auto LOG_RETENTION_DAYS = 30;
}

// 自定义事件处理器
class OrderEventHandler : 
    public EventHandler<OrderEvent>,
    public EventHandler<TradeEvent>,
    public EventHandler<ErrorEvent> {
public:
    void handle(const OrderEvent& event) override {
        SPDLOG_INFO("订单状态更新:");
        PrintUtils::printOrder(event.order);
    }
    
    void handle(const TradeEvent& event) override {
        SPDLOG_INFO("收到成交回报:");
        PrintUtils::printTrade(event.trade);
    }
    
    void handle(const ErrorEvent& event) override {
        SPDLOG_ERROR("订单处理错误: {}", event.error.message);
    }
};

// 性能监控配置
struct PerformanceConfig {
    std::chrono::milliseconds statsInterval{5000};
    size_t historySize{3600}; // 1小时数据(5秒间隔)
    std::unordered_map<std::string, double> alertThresholds{
        {"order_latency", 50.0}, // 50ms
        {"cpu_usage", 90.0},    // 90%
        {"memory_usage", 80.0}  // 80%
    };
};

// 系统初始化器
class SystemInitializer {
public:
    SystemInitializer() {
        // 初始化性能监控
        PerformanceMonitor::Config config;
        config.historySize = perfConfig_.historySize;
        config.alertHandler = [this](const std::string& metric, double value) {
            handlePerformanceAlert(metric, value);
        };
        PerformanceMonitor::instance().configure(config);
        PerformanceMonitor::instance().start();
        
        // 初始化日志系统
        logManager_.setRetentionDays(LOG_RETENTION_DAYS);
        logManager_.setMaxLogSize(MAX_LOG_SIZE);
        logManager_.setMaxLogFiles(MAX_LOG_FILES);
        logManager_.setAsyncMode(true);
        logManager_.initialize();

        // 初始化线程池
        threadPool_ = std::make_shared<ThreadPool>(std::thread::hardware_concurrency());
    }

    bool initializeComponents() {
        // 加载配置
        if (!loadConfig()) {
            return false;
        }

        // 初始化风控系统
        if (!initRiskSystem()) {
            return false;
        }

        // 初始化订单系统
        return initOrderSystem();
    }

    std::shared_ptr<hft::OrderManager> getOrderManager() const {
        return orderManager_;
    }

    void shutdown() {
        if (orderManager_) {
            orderManager_->shutdown();
        }
        PerformanceMonitor::instance().stop();
    }

private:
    bool loadConfig() {
        try {
            auto newConfig = ConfigLoader::load(CONFIG_FILE);
            if (!validateConfig(newConfig)) {
                SPDLOG_ERROR("配置验证失败");
                return false;
            }
            
            // 应用新配置
            std::lock_guard<std::mutex> lock(configMutex_);
            config_ = std::move(newConfig);
            lastConfigUpdate_ = std::chrono::system_clock::now();
            
            SPDLOG_INFO("配置热重载成功");
            return true;
        } catch (const std::exception& e) {
            SPDLOG_CRITICAL("加载系统配置失败: {}", e.what());
            return false;
        }
    }

    bool validateConfig(const json& config) {
        // 实现配置验证逻辑
        return true;
    }

    void startConfigWatcher() {
        configWatcher_ = std::thread([this]() {
            auto lastWriteTime = ConfigLoader::getLastWriteTime(CONFIG_FILE);
            while (running_) {
                try {
                    auto currentWriteTime = ConfigLoader::getLastWriteTime(CONFIG_FILE);
                    if (currentWriteTime > lastWriteTime) {
                        if (!loadConfig()) {
                            SPDLOG_WARN("配置热重载失败，使用旧配置");
                        }
                        lastWriteTime = currentWriteTime;
                    }
                    std::this_thread::sleep_for(std::chrono::seconds(1));
                } catch (...) {
                    // 忽略异常继续运行
                }
            }
        });
    }

    bool initRiskSystem() {
        try {
            riskManager_ = std::make_shared<hft::RiskManager>(
                ConfigLoader::loadRiskConfig(RISK_CONFIG_FILE));
            return true;
        } catch (const std::exception& e) {
            SPDLOG_CRITICAL("初始化风控系统失败: {}", e.what());
            return false;
        }
    }

    bool initOrderSystem() {
        try {
            orderManager_ = std::make_shared<hft::OrderManager>(riskManager_);
            orderManager_->setThreadPool(threadPool_);
            
            // 配置CTP连接参数
            CTPConfig ctpConfig;
            ctpConfig.maxRetryCount = 3;
            ctpConfig.retryInterval = std::chrono::seconds(5);
            ctpConfig.heartbeatInterval = std::chrono::seconds(10);
            ctpConfig.timeout = std::chrono::seconds(30);
            orderManager_->setCTPConfig(ctpConfig);

            // 设置行情接收限制
            MarketDataConfig mdConfig;
            mdConfig.maxRate = 10000; // 10,000 msgs/sec
            mdConfig.maxPriceChange = 0.05; // 5% max change
            mdConfig.enableValidation = true;
            orderManager_->setMarketDataConfig(mdConfig);

            return orderManager_->initialize();
        } catch (const std::exception& e) {
            SPDLOG_CRITICAL("初始化订单系统失败: {}", e.what());
            return false;
        }
    }

    LogManager logManager_;
    std::shared_ptr<ThreadPool> threadPool_;
    std::shared_ptr<hft::RiskManager> riskManager_;
    std::shared_ptr<hft::OrderManager> orderManager_;
    nlohmann::json config_;
};

// 行情数据校验器
class MarketDataValidator {
public:
    bool validate(const MarketData& data) {
        // 价格合理性检查
        if (data.lastPrice <= 0 || data.lastPrice > 1e6) {
            SPDLOG_WARN("异常价格: {}", data.lastPrice);
            return false;
        }

        // 价格跳变检查
        if (lastPrice_ > 0) {
            double change = std::abs(data.lastPrice - lastPrice_) / lastPrice_;
            if (change > maxPriceChange_) {
                SPDLOG_WARN("价格跳变过大: {}%", change * 100);
                return false;
            }
        }

        // 时间戳检查
        auto now = std::chrono::system_clock::now();
        auto dataTime = std::chrono::system_clock::from_time_t(data.timestamp);
        if (now - dataTime > std::chrono::seconds(10)) {
            SPDLOG_WARN("过期行情数据: {}秒延迟", 
                std::chrono::duration_cast<std::chrono::seconds>(now - dataTime).count());
            return false;
        }

        lastPrice_ = data.lastPrice;
        return true;
    }

private:
    double lastPrice_ = 0;
    double maxPriceChange_ = 0.05; // 5%
};

// 订单处理器
class SystemStateSaver {
public:
    explicit SystemStateSaver(const std::string& saveDir)
        : saveDir_(saveDir), 
          lastSaveTime_(std::chrono::steady_clock::now()),
          encryptor_(std::make_shared<AES256Encryptor>()) {
        if (!fs::exists(saveDir_)) {
            fs::create_directories(saveDir_);
        }
    }

    bool saveState(const SystemState& state) {
        try {
            std::string filename = saveDir_ + "/state_" + 
                std::to_string(std::time(nullptr)) + ".bin";
            
            std::ofstream file(filename, std::ios::binary);
            if (!file) return false;

            // 序列化状态
            std::ostringstream oss;
            {
                cereal::BinaryOutputArchive archive(oss);
                archive(state);
            }

            // 加密数据
            auto encrypted = encryptor_->encrypt(oss.str());
            file.write(encrypted.data(), encrypted.size());
            
            lastSaveTime_ = std::chrono::steady_clock::now();
            return true;
        } catch (...) {
            return false;
        }
    }

    std::optional<SystemState> loadLatestState() {
        // 查找最新的状态文件
        std::string latestFile;
        std::time_t latestTime = 0;
        
        for (const auto& entry : fs::directory_iterator(saveDir_)) {
            if (entry.path().extension() == ".bin") {
                auto filename = entry.path().filename().string();
                auto timeStr = filename.substr(6, filename.size() - 10);
                std::time_t fileTime = std::stol(timeStr);
                
                if (fileTime > latestTime) {
                    latestTime = fileTime;
                    latestFile = entry.path().string();
                }
            }
        }

        if (latestFile.empty()) return std::nullopt;

        // 读取并解密文件
        std::ifstream file(latestFile, std::ios::binary);
        std::string encrypted((std::istreambuf_iterator<char>(file)), 
                            std::istreambuf_iterator<char>());
        
        try {
            auto decrypted = encryptor_->decrypt(encrypted);
            std::istringstream iss(decrypted);
            
            SystemState state;
            {
                cereal::BinaryInputArchive archive(iss);
                archive(state);
            }
            
            return state;
        } catch (...) {
            return std::nullopt;
        }
    }

private:
    std::string saveDir_;
    std::chrono::steady_clock::time_point lastSaveTime_;
    std::shared_ptr<Encryptor> encryptor_;
};

class OrderCallback {
public:
    virtual ~OrderCallback() = default;
    
    // 订单状态变化回调
    virtual void onOrderStatus(const Order& order, OrderStatus status) = 0;
    
    // 成交回报回调
    virtual void onTrade(const Trade& trade) = 0;
    
    // 错误回调
    virtual void onError(const OrderError& error) = 0;
};

// 前向声明
class IOrderHandler;
class IStateManager;
class ICallbackDispatcher;

#include "order_handler_impl.h"
#include "state_manager_impl.h"
#include "callback_dispatcher_impl.h"

class OrderProcessor {
public:
    static std::unique_ptr<OrderProcessor> create(
        std::shared_ptr<hft::OrderManager> manager,
        const std::string& stateSavePath = "./system_state") {
        
        auto validator = std::make_unique<MarketDataValidator>();
        auto limiter = std::make_unique<RateLimiter>(1000); // 1000 orders/sec
        auto orderHandler = std::make_unique<OrderHandlerImpl>(
            manager, std::move(validator), std::move(limiter));
            
        auto stateManager = std::make_unique<StateManagerImpl>(stateSavePath);
        auto callbackDispatcher = std::make_unique<CallbackDispatcherImpl>();
        
        return std::make_unique<OrderProcessor>(
            std::move(manager),
            std::move(orderHandler),
            std::move(stateManager),
            std::move(callbackDispatcher));
    }

    // 保持原有公共接口
    void registerCallback(std::shared_ptr<OrderCallback> callback) {
        callbackDispatcher_->registerCallback(std::move(callback));
    }

    void processBatch(const std::vector<Order>& orders) {
        orderHandler_->processBatch(orders);
    }

    void saveState() {
        stateManager_->saveState();
    }

    bool restoreState() {
        return stateManager_->restoreState();
    }

private:
    OrderProcessor(std::shared_ptr<hft::OrderManager> manager,
                 std::unique_ptr<IOrderHandler> orderHandler,
                 std::unique_ptr<IStateManager> stateManager,
                 std::unique_ptr<ICallbackDispatcher> callbackDispatcher)
        : manager_(std::move(manager)),
          orderHandler_(std::move(orderHandler)),
          stateManager_(std::move(stateManager)),
          callbackDispatcher_(std::move(callbackDispatcher)) {

    void registerCallback(std::shared_ptr<OrderCallback> callback) {
        std::lock_guard<std::mutex> lock(callbackMutex_);
        callbacks_.push_back(callback);
    }

    void unregisterCallback(std::shared_ptr<OrderCallback> callback) {
        std::lock_guard<std::mutex> lock(callbackMutex_);
        callbacks_.erase(
            std::remove(callbacks_.begin(), callbacks_.end(), callback),
            callbacks_.end());
    }
        
        // 尝试加载最新状态
        if (auto state = stateSaver_.loadLatestState()) {
            std::lock_guard<std::mutex> lock(stateMutex_);
            manager_->restoreState(*state);
            SPDLOG_INFO("成功恢复系统状态");
        }
    }

    void processBatch() {
        // 检查CTP连接状态
        checkCTPConnection();
        if (manager_->getCTPStatus() == CTPStatus::DISCONNECTED) {
            std::this_thread::sleep_for(std::chrono::milliseconds(100));
            return;
        }

        // 检查是否需要自动保存
        auto now = std::chrono::steady_clock::now();
        if (now - lastSaveTime_ > std::chrono::minutes(5)) {
            saveSystemState();
        }

        // 动态调整批量大小
        adjustBatchSize();

        // 获取批量订单
        auto orders = manager_->getOrders(batchSize_);

        // 处理完成后保存状态
        if (!orders.empty()) {
            saveSystemState();
        }
        if (orders.empty()) {
            std::this_thread::sleep_for(std::chrono::milliseconds(1));
            return;
        }

        // 应用流量控制
        rateLimiter_.acquire(orders.size());

        // 处理批量订单
        auto start = std::chrono::steady_clock::now();
        manager_->processOrders(orders);
        auto end = std::chrono::steady_clock::now();

        // 记录性能指标
        auto latency = std::chrono::duration_cast<std::chrono::microseconds>(end - start);
        PerformanceMonitor::instance().record("order_latency", latency.count() / 1000.0);
        PerformanceMonitor::instance().record("order_rate", orders.size() * 1000.0 / latency.count());

        lastBatchTime_ = end;
    }

private:
    void notifyOrderStatus(const Order& order, OrderStatus status) {
        EventBus::instance().publish(OrderEvent{order, status});
    }

    void notifyTrade(const Trade& trade) {
        EventBus::instance().publish(TradeEvent{trade});
    }

    void notifyError(const OrderError& error) {
        EventBus::instance().publish(ErrorEvent{error});
    }

    void adjustBatchSize() {
        // 根据系统负载动态调整批量大小
        auto load = PerformanceMonitor::instance().getLoad();
        if (load < 0.3) {
            batchSize_ = std::min(batchSize_ + 2, 50);
        } else if (load > 0.7) {
            batchSize_ = std::max(batchSize_ - 1, 1);
        }
    }

    // CTP连接监控
    void checkCTPConnection() {
        auto status = manager_->getCTPStatus();
        if (status == CTPStatus::DISCONNECTED) {
            if (lastDisconnectTime_ == std::chrono::steady_clock::time_point()) {
                lastDisconnectTime_ = std::chrono::steady_clock::now();
            } else {
                auto elapsed = std::chrono::steady_clock::now() - lastDisconnectTime_;
                if (elapsed > std::chrono::seconds(30)) {
                    SPDLOG_ERROR("CTP长时间断开连接，尝试重新初始化");
                    manager_->reinitializeCTP();
                    lastDisconnectTime_ = std::chrono::steady_clock::time_point();
                }
            }
        } else {
            lastDisconnectTime_ = std::chrono::steady_clock::time_point();
        }
    }

    void saveSystemState() {
        std::lock_guard<std::mutex> lock(stateMutex_);
        
        try {
            SystemState state;
            state.timestamp = std::time(nullptr);
            
            // 收集订单状态
            state.orderState = manager_->getOrderState();
            
            // 收集风险控制状态
            state.riskState = manager_->getRiskManager()->getState();
            
            // 收集连接状态
            state.connectionState = manager_->getCTPStatus();
            
            // 保存状态
            if (stateSaver_.saveState(state)) {
                lastSaveTime_ = std::chrono::steady_clock::now();
                SPDLOG_INFO("系统状态保存成功");
            } else {
                SPDLOG_WARN("系统状态保存失败");
            }
        } catch (const std::exception& e) {
            SPDLOG_ERROR("保存系统状态时发生异常: {}", e.what());
        }
    }

    std::shared_ptr<hft::OrderManager> manager_;
    std::chrono::steady_clock::time_point lastBatchTime_;
    std::chrono::steady_clock::time_point lastDisconnectTime_;
    size_t batchSize_;
    RateLimiter rateLimiter_;
    SystemStateSaver stateSaver_;
    std::chrono::steady_clock::time_point lastSaveTime_;
    std::mutex stateMutex_;
};

// 测试模式配置
enum class TestMode {
    NONE,
    SIMULATION,
    REPLAY,
    STRESS_TEST
};

int main(int argc, char* argv[]) {
    // 解析命令行参数
    TestMode testMode = TestMode::NONE;
    if (argc > 1) {
        std::string mode(argv[1]);
        if (mode == "--simulation") {
            testMode = TestMode::SIMULATION;
        } else if (mode == "--replay") {
            testMode = TestMode::REPLAY;
        } else if (mode == "--stress-test") {
            testMode = TestMode::STRESS_TEST;
        }
    }

    // 设置信号处理
    std::atomic<bool> running{true};
    auto handleSignal = [&](int) {
        running = false;
        SPDLOG_INFO("收到终止信号，开始优雅关闭...");
    };

    signal(SIGINT, handleSignal);
    signal(SIGTERM, handleSignal);

    // 初始化测试环境
    std::unique_ptr<TestEnvironment> testEnv;
    if (testMode != TestMode::NONE) {
        SPDLOG_INFO("初始化测试模式: {}", static_cast<int>(testMode));
        testEnv = createTestEnvironment(testMode);
        testEnv->setup();
    }

// 自定义回调处理器
class OrderEventHandler : public hft::OrderCallback {
public:
    void onOrder(const hft::Order& order) override {
        SPDLOG_INFO("订单状态更新:");
        PrintUtils::printOrder(order);
    }
    
    void onTrade(const hft::Trade& trade) override {
        SPDLOG_INFO("收到成交回报:");
        PrintUtils::printTrade(trade);
    }
    
    void onError(const std::string& error) override {
        SPDLOG_ERROR("订单处理错误: {}", error);
    }
};

// 性能监控配置
struct PerformanceConfig {
    std::chrono::milliseconds statsInterval{5000};
    size_t historySize{3600}; // 1小时数据(5秒间隔)
    std::unordered_map<std::string, double> alertThresholds{
        {"order_latency", 50.0}, // 50ms
        {"cpu_usage", 90.0},    // 90%
        {"memory_usage", 80.0}  // 80%
    };
};

// 系统初始化器
class SystemInitializer {
public:
    SystemInitializer() {
        // 初始化性能监控
        PerformanceMonitor::Config config;
        config.historySize = perfConfig_.historySize;
        config.alertHandler = [this](const std::string& metric, double value) {
            handlePerformanceAlert(metric, value);
        };
        PerformanceMonitor::instance().configure(config);
        PerformanceMonitor::instance().start();
        
        // 初始化日志系统
        logManager_.setRetentionDays(LOG_RETENTION_DAYS);
        logManager_.setMaxLogSize(MAX_LOG_SIZE);
        logManager_.setMaxLogFiles(MAX_LOG_FILES);
        logManager_.setAsyncMode(true);
        logManager_.initialize();

        // 初始化线程池
        threadPool_ = std::make_shared<ThreadPool>(std::thread::hardware_concurrency());
    }

    bool initializeComponents() {
        // 加载配置
        if (!loadConfig()) {
            return false;
        }

        // 初始化风控系统
        if (!initRiskSystem()) {
            return false;
        }

        // 初始化订单系统
        return initOrderSystem();
    }

    std::shared_ptr<hft::OrderManager> getOrderManager() const {
        return orderManager_;
    }

    void shutdown() {
        if (orderManager_) {
            orderManager_->shutdown();
        }
        PerformanceMonitor::instance().stop();
    }

private:
    bool loadConfig() {
        try {
            auto newConfig = ConfigLoader::load(CONFIG_FILE);
            if (!validateConfig(newConfig)) {
                SPDLOG_ERROR("配置验证失败");
                return false;
            }
            
            // 应用新配置
            std::lock_guard<std::mutex> lock(configMutex_);
            config_ = std::move(newConfig);
            lastConfigUpdate_ = std::chrono::system_clock::now();
            
            SPDLOG_INFO("配置热重载成功");
            return true;
        } catch (const std::exception& e) {
            SPDLOG_CRITICAL("加载系统配置失败: {}", e.what());
            return false;
        }
    }

    bool validateConfig(const json& config) {
        // 实现配置验证逻辑
        return true;
    }

    void startConfigWatcher() {
        configWatcher_ = std::thread([this]() {
            auto lastWriteTime = ConfigLoader::getLastWriteTime(CONFIG_FILE);
            while (running_) {
                try {
                    auto currentWriteTime = ConfigLoader::getLastWriteTime(CONFIG_FILE);
                    if (currentWriteTime > lastWriteTime) {
                        if (!loadConfig()) {
                            SPDLOG_WARN("配置热重载失败，使用旧配置");
                        }
                        lastWriteTime = currentWriteTime;
                    }
                    std::this_thread::sleep_for(std::chrono::seconds(1));
                } catch (...) {
                    // 忽略异常继续运行
                }
            }
        });
    }

    bool initRiskSystem() {
        try {
            riskManager_ = std::make_shared<hft::RiskManager>(
                ConfigLoader::loadRiskConfig(RISK_CONFIG_FILE));
            return true;
        } catch (const std::exception& e) {
            SPDLOG_CRITICAL("初始化风控系统失败: {}", e.what());
            return false;
        }
    }

    bool initOrderSystem() {
        try {
            orderManager_ = std::make_shared<hft::OrderManager>(riskManager_);
            orderManager_->setThreadPool(threadPool_);
            
            // 配置CTP连接参数
            CTPConfig ctpConfig;
            ctpConfig.maxRetryCount = 3;
            ctpConfig.retryInterval = std::chrono::seconds(5);
            ctpConfig.heartbeatInterval = std::chrono::seconds(10);
            ctpConfig.timeout = std::chrono::seconds(30);
            orderManager_->setCTPConfig(ctpConfig);

            // 设置行情接收限制
            MarketDataConfig mdConfig;
            mdConfig.maxRate = 10000; // 10,000 msgs/sec
            mdConfig.maxPriceChange = 0.05; // 5% max change
            mdConfig.enableValidation = true;
            orderManager_->setMarketDataConfig(mdConfig);

            return orderManager_->initialize();
        } catch (const std::exception& e) {
            SPDLOG_CRITICAL("初始化订单系统失败: {}", e.what());
            return false;
        }
    }

    LogManager logManager_;
    std::shared_ptr<ThreadPool> threadPool_;
    std::shared_ptr<hft::RiskManager> riskManager_;
    std::shared_ptr<hft::OrderManager> orderManager_;
    nlohmann::json config_;
};

// 行情数据校验器
class MarketDataValidator {
public:
    bool validate(const MarketData& data) {
        // 价格合理性检查
        if (data.lastPrice <= 0 || data.lastPrice > 1e6) {
            SPDLOG_WARN("异常价格: {}", data.lastPrice);
            return false;
        }

        // 价格跳变检查
        if (lastPrice_ > 0) {
            double change = std::abs(data.lastPrice - lastPrice_) / lastPrice_;
            if (change > maxPriceChange_) {
                SPDLOG_WARN("价格跳变过大: {}%", change * 100);
                return false;
            }
        }

        // 时间戳检查
        auto now = std::chrono::system_clock::now();
        auto dataTime = std::chrono::system_clock::from_time_t(data.timestamp);
        if (now - dataTime > std::chrono::seconds(10)) {
            SPDLOG_WARN("过期行情数据: {}秒延迟", 
                std::chrono::duration_cast<std::chrono::seconds>(now - dataTime).count());
            return false;
        }

        lastPrice_ = data.lastPrice;
        return true;
    }

private:
    double lastPrice_ = 0;
    double maxPriceChange_ = 0.05; // 5%
};

// 订单处理器
class OrderProcessor {
public:
    explicit OrderProcessor(std::shared_ptr<hft::OrderManager> manager)
        : manager_(std::move(manager)),
          lastBatchTime_(std::chrono::steady_clock::now()),
          batchSize_(10),
          rateLimiter_(1000), // 1000 orders/second
          mdValidator_() {}

    void processBatch() {
        // 检查CTP连接状态
        checkCTPConnection();
        if (manager_->getCTPStatus() == CTPStatus::DISCONNECTED) {
            std::this_thread::sleep_for(std::chrono::milliseconds(100));
            return;
        }

        // 动态调整批量大小
        adjustBatchSize();

        // 获取批量订单
        auto orders = manager_->getOrders(batchSize_);
        if (orders.empty()) {
            std::this_thread::sleep_for(std::chrono::milliseconds(1));
            return;
        }

        // 应用流量控制
        rateLimiter_.acquire(orders.size());

        // 处理批量订单
        auto start = std::chrono::steady_clock::now();
        manager_->processOrders(orders);
        auto end = std::chrono::steady_clock::now();

        // 记录性能指标
        auto latency = std::chrono::duration_cast<std::chrono::microseconds>(end - start);
        PerformanceMonitor::instance().record("order_latency", latency.count() / 1000.0);
        PerformanceMonitor::instance().record("order_rate", orders.size() * 1000.0 / latency.count());

        lastBatchTime_ = end;
    }

private:
    void adjustBatchSize() {
        // 根据系统负载动态调整批量大小
        auto load = PerformanceMonitor::instance().getLoad();
        if (load < 0.3) {
            batchSize_ = std::min(batchSize_ + 2, 50);
        } else if (load > 0.7) {
            batchSize_ = std::max(batchSize_ - 1, 1);
        }
    }

    // CTP连接监控
    void checkCTPConnection() {
        auto status = manager_->getCTPStatus();
        if (status == CTPStatus::DISCONNECTED) {
            if (lastDisconnectTime_ == std::chrono::steady_clock::time_point()) {
                lastDisconnectTime_ = std::chrono::steady_clock::now();
            } else {
                auto elapsed = std::chrono::steady_clock::now() - lastDisconnectTime_;
                if (elapsed > std::chrono::seconds(30)) {
                    SPDLOG_ERROR("CTP长时间断开连接，尝试重新初始化");
                    manager_->reinitializeCTP();
                    lastDisconnectTime_ = std::chrono::steady_clock::time_point();
                }
            }
        } else {
            lastDisconnectTime_ = std::chrono::steady_clock::time_point();
        }
    }

    std::shared_ptr<hft::OrderManager> manager_;
    std::chrono::steady_clock::time_point lastBatchTime_;
    std::chrono::steady_clock::time_point lastDisconnectTime_;
    size_t batchSize_;
    RateLimiter rateLimiter_;
};

// 测试模式配置
enum class TestMode {
    NONE,
    SIMULATION,
    REPLAY,
    STRESS_TEST
};

int main(int argc, char* argv[]) {
    // 解析命令行参数
    TestMode testMode = TestMode::NONE;
    if (argc > 1) {
        std::string mode(argv[1]);
        if (mode == "--simulation") {
            testMode = TestMode::SIMULATION;
        } else if (mode == "--replay") {
            testMode = TestMode::REPLAY;
        } else if (mode == "--stress-test") {
            testMode = TestMode::STRESS_TEST;
        }
    }

    // 设置信号处理
    std::atomic<bool> running{true};
    auto handleSignal = [&](int) {
        running = false;
        SPDLOG_INFO("收到终止信号，开始优雅关闭...");
    };

    signal(SIGINT, handleSignal);
    signal(SIGTERM, handleSignal);

    // 初始化测试环境
    std::unique_ptr<TestEnvironment> testEnv;
    if (testMode != TestMode::NONE) {
        SPDLOG_INFO("初始化测试模式: {}", static_cast<int>(testMode));
        testEnv = createTestEnvironment(testMode);
        testEnv->setup();
    }

    try {
        // 系统初始化
        SystemInitializer initializer;
        if (!initializer.initializeComponents()) {
            return 1;
        }

        // 安全审计初始化
        SecurityAudit::initialize("security_audit.log");
        SecurityAudit::logEvent(SystemEvent::STARTUP, "系统启动");

        auto orderManager = initializer.getOrderManager();

        // 设置权限控制
        orderManager->setAccessController(
            std::make_shared<RoleBasedAccessControl>());

        // 启用数据加密
        if (ConfigManager::getBool("security.enable_encryption", true)) {
            orderManager->enableEncryption(
                std::make_shared<AES256Encryptor>(
                    ConfigManager::getString("security.encryption_key")));
        }

        // 配置日志器
        auto system_logger = spdlog::get("system");
        system_logger->set_pattern("[%Y-%m-%d %H:%M:%S.%e] [%^%l%$] [SYSTEM] %v");
        
        auto trade_logger = spdlog::get("trade");
        trade_logger->set_pattern("[%Y-%m-%d %H:%M:%S.%e] [TRADE] %v");
        
        auto error_logger = spdlog::get("error");
        error_logger->set_pattern("[%Y-%m-%d %H:%M:%S.%e] [%^%l%$] [ERROR] %v");

        spdlog::flush_every(LOG_FLUSH_INTERVAL);
        spdlog::flush_on(spdlog::level::warn);
        spdlog::set_default_logger(system_logger);

        // 记录系统启动信息
        SPDLOG_INFO("高频交易系统启动");
        trade_logger->info("交易日志系统初始化完成");

        // 创建并注册事件处理器
        auto event_handler = std::make_shared<OrderEventHandler>();

        EventBus::instance().subscribe<OrderEvent>(event_handler);
        EventBus::instance().subscribe<TradeEvent>(event_handler);
        EventBus::instance().subscribe<ErrorEvent>(event_handler);

        // 主事件循环
        EventLoop eventLoop;
        eventLoop.registerHandler([&]() {
            // 心跳检测
            static auto lastHeartbeat = std::chrono::steady_clock::now();
            auto now = std::chrono::steady_clock::now();
            if (std::chrono::duration_cast<std::chrono::seconds>(now - lastHeartbeat) >= MONITOR_INTERVAL) {
                PerformanceMonitor::instance().logStats();
                lastHeartbeat = now;
            }
            return running.load();
        });

        // 启动订单处理线程
        auto orderProcessing = std::async(std::launch::async, [&]() {
            OrderProcessor processor(orderManager);
            while (running) {
                try {
                    processor.processBatch();
                } catch (const std::exception& e) {
                    SPDLOG_ERROR("订单处理异常: {}", e.what());
                    std::this_thread::sleep_for(std::chrono::milliseconds(100));
                }
            }
        });

        // 主循环
        while (running) {
            eventLoop.runOnce();
            std::this_thread::sleep_for(std::chrono::milliseconds(10));
        }

        // 优雅关闭
        SPDLOG_INFO("等待订单处理完成...");
        orderProcessing.wait();
        initializer.shutdown();

        // 保存状态
        SystemStateSaver::save(STATE_FILE);

        SPDLOG_INFO("系统正常退出");
        return 0;
    } catch (const std::exception& e) {
        SPDLOG_CRITICAL("系统异常终止: {}", e.what());
        return 1;
    }
}